﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Linq;
using MS.InformationManagement.Support.Constants;
using System.Web;
using Microsoft.SharePoint.WebControls;
using Office = Microsoft.Office.DocumentManagement.DocumentSets;

namespace MS.InformationManagement.BLL.GenerarSolicitudPrestamos
{
    public class GenerarSolicitudPrestamos
    {
        public static Radicado GetRadicado(Guid libraryGuid, int itemID)
        {
            Microsoft.SharePoint.SPList targetList = SPContext.Current.Web.Lists.GetList(libraryGuid, false);
            SPListItem item = targetList.GetItemById(itemID);

            if (item == null)
                return null;

            Radicado foundDocument = new Radicado();
            foundDocument.DocumentIDValue = item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID] + "";
            foundDocument.NúmeroExpediente = item[CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID] + "";
            foundDocument.Created = DateTime.Parse(item[SPBuiltInFieldId.Created] + "");
            foundDocument.Asunto = item[CustomSiteColumns.FIELD_DOCSET_ASUNTO] + "";
            foundDocument.TipoDocumento = item[CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE] + "";
            foundDocument.RemitenteDestinatario = item[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT] + "";

            if (!PuedoPrestar(foundDocument.DocumentIDValue))
                return null;

            if (!PuedoPrestar(foundDocument.NúmeroExpediente))
                return null;

            return foundDocument;
        }

        public static bool GenerarSolicitud(Guid libraryGuid,int itemID, string IdRadicado, string ObservacionesSolicitud, TipoDePrestamo TipoPrestamo)
        {
            bool result = false;
            SPUser currentUser =  SPContext.Current.Web.CurrentUser;
            Microsoft.SharePoint.SPList targetList = SPContext.Current.Web.Lists.GetList(libraryGuid, false);
            SPListItem item = targetList.GetItemById(itemID);
            string radicador = item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED] + "";
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPUserToken systoken = SPContext.Current.Site.SystemAccount.UserToken;
                    using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url, systoken))
                    {
                        using (SPWeb currentWeb = currentSite.OpenWeb())
                        {
                            //Linq have acces denaid
                            currentWeb.AllowUnsafeUpdates = true;
                            SPUser userPrestamos = currentWeb.EnsureUser(radicador);
                            SPList listPrestamos = currentWeb.Lists.TryGetList(GlobalConstants.LIST_PRESTAMOS);
                            SPListItem newItem = listPrestamos.Items.Add();
                            newItem[CustomSiteColumns.FIELD_SOLICITUD_PRESTAMOS_USER_SOLICITUD] = currentUser;
                            newItem[CustomSiteColumns.FIELD_SOLICITUD_PRESTAMOS_OBS_SOLICITUD] = ObservacionesSolicitud;
                            newItem[CustomSiteColumns.FIELD_SOLICITUD_PRESTAMOS_USER_DEPT_SOLICITUD] = new MS.InformationManagement.BLL.GestionDeUsuarios.GestionDeUsuariosBLL().getProperty(GlobalConstants.UP_DEPARTMENT, SPContext.Current.Web.CurrentUser.LoginName);
                            newItem[CustomSiteColumns.FIELD_SOLICITUD_PRESTAMOS_TIPO] = TipoPrestamo;
                            newItem[CustomSiteColumns.FIELD_SOLICITUD_PRESTAMOS_ID_RADICADO] = IdRadicado;
                            newItem[CustomSiteColumns.FIELD_SOLICITUD_PRESTAMOS_USER_PRESTAMO] = userPrestamos;
                            newItem[CustomSiteColumns.FIELD_SOLICITUD_PRESTAMOS_ESTADO] = string.Empty;
                            newItem[CustomSiteColumns.FIELD_SOLICITUD_PRESTAMOS_USER_DEPT_PRESTAMO] = new MS.InformationManagement.BLL.GestionDeUsuarios.GestionDeUsuariosBLL().getProperty(GlobalConstants.UP_DEPARTMENT, userPrestamos.LoginName);
                            newItem[SPBuiltInFieldId.Author] = currentUser;
                            newItem.Update();
                            currentWeb.AllowUnsafeUpdates = false;
                            result = true;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return result;
        }

        private static bool PuedoPrestar(string IdRadicado)
        {
            bool result = true;

            SPQuery query = new SPQuery();
            query.Query = string.Format("<Where><And><And><Eq><FieldRef Name='Prestamos_Id' /><Value Type='Text'>{0}</Value></Eq><Neq><FieldRef Name='Prestamos_Estado' /><Value Type='Choice'>Cancelado</Value></Neq></And><And><And><Eq><FieldRef Name='Prestamos_Id' /><Value Type='Text'>{0}</Value></Eq><Neq><FieldRef Name='Prestamos_Estado' /><Value Type='Choice'>Rechazado</Value></Neq></And><And><Eq><FieldRef Name='Prestamos_Id' /><Value Type='Text'>{0}</Value></Eq><Neq><FieldRef Name='Prestamos_Estado' /><Value Type='Choice'>Devuelto</Value></Neq></And></And></And></Where>", IdRadicado);
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPUserToken systoken = SPContext.Current.Site.SystemAccount.UserToken;
                using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url, systoken))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        SPList prestamosList = currentWeb.Lists.TryGetList(GlobalConstants.LIST_PRESTAMOS);
                        if (prestamosList != null)
                        {
                            SPListItemCollection resultColl = prestamosList.GetItems(query);
                            if (resultColl.Count > 0)
                                result = false;
                        }
                    }
                }
            });

            return result;
        }
    }
}
